<template>
  <div class="logistics_add">
    <div class="add_con">
      <div class="add_head">
        <div class="add_title">
          <span>{{ Number(formData.month) }}</span>
          <span>月办公用品领用单</span>
          <span v-if="formData.applyType === '2'">（临时）</span>
        </div>
        <div class="add_info">
          <div class="info_radio"></div>
          <div class="info_del">
            <div class="del_org">部门名称：{{ formData.orgName }}</div>
            <div class="del_num">总人数：{{ formData.headCount }}</div>
          </div>
        </div>
      </div>
      <div class="add_table" ref="add_table">
        <div class="log_add_tab">
          <el-form :model="formData" ref="ruleForm">
            <!-- stripe -->
            <el-table
              :data="formData.tableData"
              border
              style="width: 100%"
              :header-cell-class-name="headerStyle"
              :row-class-name="rowClass">
              <el-table-column label="物品名称" align="center" width="200">
                <template slot-scope="scope">
                  <div class="cell_show" v-if="!scope.row.isEdit">
                    {{ scope.row.name }}
                  </div>
                  <el-form-item v-else :prop="'tableData.' + scope.$index + '.name'" :rules="moduleListRules.name">
                    <el-select
                      v-model="scope.row.name"
                      placeholder="请选择"
                      size="medium"
                      @change="changeOrg2($event, scope.$index)"
                      popper-class="my_select"
                      ref="mySelect"
                      filterable
                      @focus="focusName($event, scope.$index)">
                      <el-option
                        v-for="item in chooseList"
                        :key="item.typeId"
                        :label="item.name"
                        :value="item.name"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="规格" align="center" width="150">
                <template slot-scope="scope">
                  <div class="cell_show" v-if="!scope.row.isEdit">
                    {{ scope.row.specs }}
                  </div>
                  <el-form-item v-else>
                    <el-input
                      v-model="scope.row.specs"
                      size="medium"
                      filterable
                      clearable
                      placeholder="请选择物品名称"
                      disabled></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="申请数量" align="center" width="120">
                <template slot-scope="scope">
                  <div class="cell_show" v-if="!scope.row.isEdit">
                    {{ scope.row.applyNumber }}
                  </div>
                  <el-form-item
                    v-else
                    :prop="'tableData.' + scope.$index + '.applyNumber'"
                    :rules="moduleListRules.applyNumber">
                    <el-input
                      v-model="scope.row.applyNumber"
                      size="medium"
                      filterable
                      clearable
                      placeholder="请输入"
                      type="number"
                      @blur="selectBlur($event, scope.$index)"
                      class="size_input"
                      maxlength="4"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center">
                <template slot-scope="scope">
                  <div class="cell_show" v-if="!scope.row.isEdit">
                    {{ scope.row.remark }}
                  </div>
                  <el-form-item v-else :prop="'tableData.' + scope.$index + '.remark'" :rules="moduleListRules.remark">
                    <el-input
                      v-model="scope.row.remark"
                      size="medium"
                      filterable
                      clearable
                      placeholder="请输入"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="czpt" label="操作" align="center" width="140" fixed="right">
                <template slot-scope="scope">
                  <div class="cell_show" v-if="scope.row.typeId">
                    <!-- <a v-if="!scope.row.isEdit" class="tableButton" href="javascript:;" @click="editRow(scope.row, scope.$index)"
                      ><i class="el-icon-edit-outline"></i> 编辑</a
                    > -->
                    <!-- <a v-else class="tableButton" href="javascript:;" @click="saveRow2(scope.row, scope.$index)"
                      ><i class="el-icon-document-checked"></i> 保存</a
                    > -->
                    <a
                      class="tableButton m-l-10"
                      href="javascript:;"
                      @click="delGood(scope.row, scope.$index)"
                      v-if="formData.tableData.length > 1">
                      <i class="el-icon-delete"></i>
                      删除
                    </a>
                  </div>
                  <div v-else>
                    <!-- <a class="tableButton" href="javascript:;" @click="saveRow2(scope.row, scope.$index)"><i class="el-icon-document-checked"></i> 保存</a> -->
                    <a class="tableButton m-l-10" href="javascript:;" @click="delRowTwo(scope.$index)">
                      <i class="el-icon-circle-close"></i>
                      取消
                    </a>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <div class="log_btn_add" @click="addRowsTwo">
          <span class="el-icon-plus color_blue">增加一条</span>
        </div>
      </div>
      <div class="add_annex">
        <div class="annex_name">附件：</div>
        <div class="annex_list">
          <UploadFile :file-list="formData.enclosureList"></UploadFile>
        </div>
      </div>
      <div class="btn_save">
        <el-button size="small" @click="cancelData">取 消</el-button>
        <el-button size="small" type="primary" @click="saveData('0')">暂 存</el-button>
        <el-button size="small" type="primary" @click="saveData('1')">提 交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { getAddDetailInfo, addLogicticsInfo, checkAddAuthority } from '@apis/api-dailyManage.js'
import moment from 'moment'
import UploadFile from '@com/UploadFile'
import { cloneDeep } from 'lodash'
export default {
  components: {
    UploadFile,
  },
  props: {},
  watch: {
    formData: {
      handler(news) {},
      deep: true,
      immediate: true,
    },
  },
  data() {
    const validName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('必选项'))
      } else {
        callback()
      }
    }
    return {
      moment: moment,
      userInfo: JSON.parse(localStorage.PSKH_USERINFO),
      formData: {
        year: moment().format('YYYY'),
        month: moment().format('MM'),
        enclosureList: [],
        tableData: [],
        applyType: '1',
        orgName: '',
        headCount: '',
      },
      moduleListRules: {
        typeId: [{ required: true, validator: validName, trigger: 'change' }],
        name: [{ required: true, validator: validName, trigger: 'change' }],
        applyNumber: [{ required: true, validator: validName, trigger: 'change' }],
      },
      editsNum: 0,
      thingList: [],
      chooseList: [],
      isEdit: false,
      activeInfo: {},
      monthData: moment().format('M'),
    }
  },
  created() {},
  mounted() {
    // this.checkAddAuthority()
    this.getAddDetailInfo()
  },
  methods: {
    getAddDetailInfo() {
      const param = {
        orgId: this.userInfo.loginPostInfo.orgId,
        applyType: this.formData.applyType,
      }
      getAddDetailInfo(param).then(res => {
        const data = res.data
        this.formData.orgName = data.orgName
        this.formData.headCount = data.headCount
        if (data.itemTypeList.length) {
          this.thingList = JSON.parse(JSON.stringify(data.itemTypeList))
          this.formData.tableData = data.itemTypeList.slice(0, 1)
          this.$set(this.formData.tableData[0], 'applyNumber', this.formData.tableData[0].defaultQty)
          this.$set(this.formData.tableData[0], 'realityNumber', this.formData.tableData[0].defaultQty)
          this.$set(this.formData.tableData[0], 'isEdit', true)
        }
      })
    },
    headerStyle({ row, column, rowIndex, columnIndex }) {
      return 'headerStyle'
    },
    rowClass({ row, rowIndex }) {
      return 'rowClass'
    },
    changeOrg2(name, index, type) {
      const arr = this.thingList.filter(li => {
        return li.name === name
      })
      const item = arr[0]
      // this.isEdit = true
      this.activeInfo = item
      this.$set(this.formData.tableData[index], 'typeId', item.typeId)
      this.$set(this.formData.tableData[index], 'name', item.name)
      this.$set(this.formData.tableData[index], 'specs', item.specs)
      this.$set(this.formData.tableData[index], 'defaultQty', item.defaultQty || 0)
      this.$set(this.formData.tableData[index], 'applyNumber', item.defaultQty || 0)
      this.$set(this.formData.tableData[index], 'realityNumber', item.defaultQty || 0)
      this.$set(this.formData.tableData[index], 'remark', item.remark)
      this.$set(this.formData.tableData[index], 'isEdit', true)
    },
    selectBlur(e, index) {
      this.formData.tableData[index].applyNumber = e.target.value
      this.formData.tableData[index].realityNumber = e.target.value
    },
    /* 编辑功能 */
    editRow(item, index, type) {
      if (this.editsNum > 0) {
        this.$alert('您有暂未保存的内容，请先保存或者取消。', '提示', {
          confirmButtonText: '确定',
        })
        return false
      }
      this.isEdit = true
      this.activeInfo = item
      this.calEditsNum(1)
      this.$set(this.formData.tableData[index], 'isEdit', true)
    },
    saveRow2(item, index) {
      if (!item.typeId || !Number(item.applyNumber)) {
        return this.$message.warning('请确认信息填写完整')
      }
      this.$set(this.formData.tableData[index], 'isEdit', false)
      this.isEdit = false
      this.calEditsNum(-1)
    },
    delGood(item, index) {
      if (this.editsNum > 0) {
        this.$alert('您有暂未保存的内容，请先保存或者取消。', '提示', {
          confirmButtonText: '确定',
        })
        return false
      }
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$message.success('删除成功')
          this.formData.tableData.splice(index, 1)
          this.calEditsNum(-1)
        })
        .catch(() => {})
    },
    delRowTwo(index) {
      this.formData.tableData.splice(index, 1)
      this.calEditsNum(-1)
    },
    // 计算编辑状态数量
    calEditsNum(num) {
      this.editsNum = this.editsNum + num
    },
    addRowsTwo() {
      if (this.editsNum > 0) {
        this.$alert('您有暂未保存的内容，请先保存或者取消。', '提示', {
          confirmButtonText: '确定',
        })
        return false
      }
      this.formData.tableData.push({
        name: '',
        typeId: '',
        defaultQty: '',
        applyNumber: '',
        realityNumber: 0,
        specs: '',
        isEdit: true,
      })
      // this.calEditsNum(1)
    },
    cancelData() {
      this.$emit('cancelData')
    },
    saveData(type) {
      let dataList = []
      if (type === '0') {
        const arr = this.formData.tableData.filter(item => {
          return !item.name
        })
        if (arr.length === this.formData.tableData.length) {
          this.$alert('请至少选择一种办公用品', '提示', {
            confirmButtonText: '确定',
          })
          return false
        }
        dataList = this.formData.tableData.filter(item => {
          return item.name
        })
      } else {
        const arr = this.formData.tableData.filter(item => {
          return !item.name || !Number(item.applyNumber)
        })
        if (arr.length > 0) {
          this.$alert('您有尚未填写完整的内容，请先完成或者取消。', '提示', {
            confirmButtonText: '确定',
          })
          return false
        }
        dataList = this.formData.tableData
      }
      // if (this.editsNum > 0) {
      //   this.$alert('您有暂未保存的内容，请先保存或者取消。', '提示', {
      //     confirmButtonText: '确定',
      //   })
      //   return false
      // }
      const title = Number(this.formData.month) + '月办公用品领用单'
      dataList.forEach((item, index) => {
        this.$set(item, 'sort', index + 1)
      })
      const param = {
        applyType: this.formData.applyType,
        enclosureList: this.formData.enclosureList,
        headCount: this.formData.headCount,
        itemTypeList: dataList,
        orgName: this.formData.orgName,
        orgId: this.userInfo.loginPostInfo.orgId,
        year: this.formData.year,
        month: Number(this.formData.month),
        title: title,
        isSave: type,
      }
      addLogicticsInfo(param).then(res => {
        if (res.code === 0) {
          if (type === '0') {
            this.$message.success('暂存成功')
          } else {
            this.$message.success('提交成功')
          }
          this.$emit('addSuccess', 'add')
        }
      })
    },
    checkAddAuthority() {
      checkAddAuthority({
        applyType: this.formData.applyType,
        orgId: this.userInfo.loginPostInfo.orgId,
      }).then(res => {
        if (res.code === 0) {
          if (res.data === '1') {
            this.getAddDetailInfo()
          } else {
            this.$confirm(res.data, '提示', {
              confirmButtonText: '确定',
              type: 'warning',
              showCancelButton: false,
              showClose: false,
              closeOnClickModal: false,
              closeOnPressEscape: false,
            })
              .then(() => {
                this.formData.applyType = '2'
                this.formData.month = moment().format('MM')
                this.formData.year = moment().format('YYYY')
                this.getAddDetailInfo()
              })
              .catch(() => {})
          }
        }
      })
    },
    focusName(name, index, type) {
      if (this.formData.tableData[index].name) {
        this.isEdit = true
      } else {
        this.isEdit = false
      }
      this.activeInfo = this.formData.tableData[index]
      const arr = cloneDeep(this.thingList)
      this.formData.tableData.forEach(item => {
        const idx = arr.findIndex(li => {
          return li.typeId === item.typeId
        })
        arr.splice(idx, 1)
      })
      if (this.isEdit && this.activeInfo.typeId) {
        const li = arr.filter(item => {
          return item.typeId === this.activeInfo.typeId
        })
        if (li.length > 0) {
          arr.unshift(this.activeInfo)
        }
      }
      this.chooseList = arr
    },
  },
}
</script>

<style lang="scss" scoped>
.logistics_add {
  width: 100%;
  height: 100%;
  font-size: 14px;
  .add_con {
    flex: 1;
    padding: 0 10px;
    .add_head {
      .add_title {
        font-size: 20px;
        font-weight: bold;
        text-align: center;
        color: #333333;
      }
      .add_info {
        font-size: 16px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 10px;
        .info_radio {
          .el-radio {
            margin-right: 20px;
          }
        }
        .info_del {
          display: flex;
          .del_org {
            margin-right: 20px;
          }
        }
      }
    }
    .add_table {
      .el-select {
        width: 100%;
      }
      /deep/.el-input__inner {
        background: #f5f6fa;
        border: none;
        border-radius: 0;
        width: 100%;
      }
      /deep/.el-textarea__inner {
        background: #f5f6fa;
        border: none;
        border-radius: 0;
        width: 100%;
      }
      /deep/.el-date-editor {
        width: 100%;
      }
      /deep/ .el-select-dropdown__item {
        padding: 0 10px;
      }
      /deep/ .el-form-item {
        padding: 2.5px 0;
        background: #f5f6fa;
        margin: 2px;
      }
      /deep/.el-form-item__content {
        background: #f5f6fa;
      }
      /deep/ .el-form-item__error {
        margin-top: -15px;
        margin-left: 15px;
      }
      .tableButton {
        color: #333;
        i {
          color: #2261b9;
          font-size: 14px;
        }
      }
      .log_btn_add {
        height: 45px;
        line-height: 45px;
        text-align: center;
        border: 1px dashed #dcdfe6;
        margin: 10px 0;
        cursor: pointer;
        &:hover {
          box-shadow: 2px 4px 12px 1px rgba(0, 0, 0, 0.4);
        }
        .color_blue {
          color: #4b79bb;
          font-weight: 600;
          font-size: 14px;
          &:not(:first-child) {
            margin-left: 40px;
          }
        }
      }
      .log_add_tab {
        padding-top: 10px;
      }
    }
    .add_annex {
      display: flex;
      .annex_name {
        margin-bottom: 20px;
        margin-right: 20px;
        padding: 9px 0;
      }
      .annex_list {
        flex: 1;
      }
    }
  }
  .tips {
    font-size: 14px;
    color: #8f939a;
  }
  .btn_save {
    margin-top: 10px;
    text-align: center;
    padding-bottom: 10px;
  }
  /deep/.el-table td,
  /deep/.el-table th.is-leaf,
  /deep/.el-table--border,
  /deep/.el-table--group {
    border-color: #d9dee4;
  }
  /deep/.el-table--border {
    border-left: 1px solid #d9dee4;
    border-right: 1px solid #d9dee4;
  }
  /deep/.headerStyle {
    background: #e7eff2;
    border-top: 1px solid #d9dee4;

    .cell {
      color: #333333;
      font-size: 14px;
      p {
        font-size: 14px;
      }
    }
  }
  /deep/.rowClass {
    td {
      padding: 0;
      position: relative;
    }
    .cell {
      color: #333;
      font-size: 14px;
      padding: 0 !important;
      .cell_show {
        padding: 12px 5px;
      }
      div,
      span,
      p {
        font-size: 14px;
      }
    }
  }
  .size_input {
    ::-webkit-outer-spin-button,
    ::-webkit-inner-spin-button {
      margin: 0;
      -webkit-appearance: none !important;
    }

    input[type='number']::-webkit-outer-spin-button,
    input[type='number']::-webkit-inner-spin-button {
      margin: 0;
      -webkit-appearance: none !important;
    }
  }
}
</style>
